package com.wenhai.liuyubobobo.imooc.tree;

import java.util.TreeMap;

/**
 * 字典树/前缀树
 *
 * @author wenhai
 * @date   2021/3/25
 */
public class Trie {
    private Node root;
    private int size;

    public Trie() {
        this.root = new Node();
        this.size = 0;
    }

    public int size() {
        return this.size;
    }

    public void add(String word) {
        Node cur = this.root;
        for (int i = 0; i < word.length(); i++) {
            char c = word.charAt(i);
            if (cur.next.get(c) == null) {
                cur.next.put(c, new Node());
            }
            cur = cur.next.get(c);
        }
        if (!cur.isWord) {
            cur.isWord = true;
            size++;
        }
    }

    public boolean contains(String word) {
        Node cur = this.root;
        for (int i = 0; i < word.length(); i++) {
            char c = word.charAt(i);
            if (cur.next.get(c) == null) {
                return false;
            }
            cur = cur.next.get(c);
        }
        return cur.isWord;
    }


    public boolean startWith(String word) {

        Node cur = this.root;
        for (int i = 0; i < word.length(); i++) {
            char c = word.charAt(i);
            if (cur.next.get(c) == null) {
                return false;
            }
            cur = cur.next.get(c);
        }
        return true;
    }


    private class Node {
        boolean isWord;
        TreeMap<Character, Node> next;

        Node() {
            this(false);
        }

        Node(boolean isWord) {
            this(isWord, new TreeMap<>());
        }

        Node(boolean isWord, TreeMap<Character, Node> next) {
            this.isWord = isWord;
            this.next = next;
        }
    }


    public static void main(String[] args) {
        Trie trie = new Trie();
        trie.add("安徽省");
        trie.add("安徽省");
        System.out.println(trie.contains("安徽省"));
        System.out.println(trie.startWith("安徽"));
        System.out.println(trie.size());
    }
}
